package com.ecart.service;

import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.ecartdb.data.Account;
import com.ecartdb.EcartDB;
import com.wavemaker.runtime.RuntimeAccess;
import com.wavemaker.runtime.javaservice.JavaServiceSuperClass;
import com.wavemaker.runtime.service.annotations.ExposeToClient;

/**
 * This is a client-facing service class.  All
 * public methods will be exposed to the client.  Their return
 * values and parameters will be passed to the client or taken
 * from the client, respectively.  This will be a singleton
 * instance, shared between all requests. 
 * 
 * To log, call the superclass method log(LOG_LEVEL, String) or log(LOG_LEVEL, String, Exception).
 * LOG_LEVEL is one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log level.
 * For info on these levels, look for tomcat/log4j documentation
 */
@ExposeToClient
public class AccountService extends JavaServiceSuperClass {
    /* Pass in one of FATAL, ERROR, WARN,  INFO and DEBUG to modify your log level;
     *  recommend changing this to FATAL or ERROR before deploying.  For info on these levels, look for tomcat/log4j documentation
     */
    public AccountService() {
       super(INFO);
    }

    public UserDetails authenticateLogin(String user,String passwd) {
     //  String result  = null;
       Account acc=new Account();


		EcartDB db = (EcartDB) RuntimeAccess.getInstance()
				.getServiceBean("ecartDB");
		UserDetails result = new UserDetails();
		try {
			log(INFO, "####### email= " + user);
			log(INFO, "####### password= " + passwd);
			
			db.begin();

			Session session = db.getDataServiceManager().getSession();

			Query query = session
					.createQuery("from Account where lower(email)= :email and password=:password and active=true");
			query.setString("email", user.toLowerCase());
			query.setString("password", passwd);
			
			List userList = query.list();

			if (userList != null && !userList.isEmpty()) {

				 acc = (Account) userList.get(0);
				System.out.println("$$$$$$$$ user found ::" + acc.getFirstName());
				result.setAccountId(acc.getAccountId());
				//result.setAccount(acc);
				result.setEmail(acc.getEmail());
				result.setAuthenticated(true);
				result.setFirstName(acc.getFirstName());
				result.setAccountRole(acc.getAccountRole());
				result.setAddress(acc.getAddress());
				result.setLastName(acc.getLastName());
				result.setCellPhone(acc.getCellPhone());
				result.setPassword(acc.getPassword());
				result.setMessage("User Logged in successfully");
				
				

			} else {
				System.out.println("User not found ");
				result.setMessage("User not found ");
				result.setAuthenticated(false);
				

			}

			log(INFO, "Returning " + result);
			
			db.commit();
		} catch (Exception e) {
			db.rollback();

			result.setMessage("User not found in the Project");
			result.setAuthenticated(false);
			log(ERROR, "Error in retrieveUserDetails;user=" + user
					+ ";password=" + passwd, e);
		}
	
	
       return result;
    }

    public Account registerAccount(Account account)  throws Exception {
        /*String result  = null;
        Account acc=new Account();
        try {
     	   
           log(INFO, "registerAccount");
           result = "registerAccount";
           log(INFO, "Returning skiranhegde@gmail.com " + result);
           account.setAccountId(100);
           acc.setAccountId(100);
           acc.setEmail("skiranhegde@gmail.com");
        } catch(Exception e) {
           log(ERROR, "The sample java service operation has failed", e);
        }
        return account;*/


    	String result = null;

    	EcartDB db = (EcartDB) RuntimeAccess.getInstance().getServiceBean("ecartDB");

    	try {

    		// log(INFO, "activationCode=" + activationCode);
    		log(INFO, "email=" + account.getEmail().toLowerCase());

    		db.begin();

    		Session session = db.getDataServiceManager().getSession();
    		// TODO: validations
    		Criteria criteria = session.createCriteria(Account.class);
    		criteria.add(Restrictions.eq("email",
    				account.getEmail().toLowerCase()).ignoreCase());
    		List results = criteria.list();
    		if (results != null && !results.isEmpty()) {
    			log(ERROR,
    					"Email id already in use.Please use different id or login using the same");
    			throw new Exception(
    					"Email id already in use.Please use different id or login using the same");
    		}

    		
    		account.setEmail(account.getEmail().toLowerCase());
    		
    		account.setUpdatedBy("SYS");
    		Calendar startingCalendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
    		account.setUpdatedTs(startingCalendar.getTime());
    		account.setActive(true);
    		account.setAccountRole("CUSTOMER");
    		session.save(account);

    	
    		System.out.println("customer::" + account.getFirstName());

    		log(INFO, "Returning *********************" + result);

    		db.commit();
    		result = "User registration successfull";
    	} catch (Exception e) {
    		db.rollback();
    		log(ERROR, "Error during registration", e);
    		throw e;
    	}
    	return account;


     }
    public Account updateAccount(Account account) throws Exception {
        /*String result  = null;
        Account acc=new Account();
        try {
     	   
           log(INFO, "registerAccount");
           result = "registerAccount";
           log(INFO, "Returning skiranhegde@gmail.com " + result);
           account.setAccountId(100);
           acc.setAccountId(100);
           acc.setEmail("skiranhegde@gmail.com");
        } catch(Exception e) {
           log(ERROR, "The sample java service operation has failed", e);
        }
        return account;*/

System.out.println("account.getEmail()"+account.getEmail());
System.out.println("acc id"+account.getAccountId());
    	String result = null;

    	EcartDB db = (EcartDB) RuntimeAccess.getInstance().getServiceBean("ecartDB");

    	try {

    		// log(INFO, "activationCode=" + activationCode);
    		log(INFO, "email=" + account.getEmail().toLowerCase());

    		db.begin();

    		Session session = db.getDataServiceManager().getSession();
    		// TODO: validations
    	/*	Criteria criteria = session.createCriteria(Account.class);
    		criteria.add(Restrictions.eq("email",
    				account.getEmail().toLowerCase()).ignoreCase());
    		List results = criteria.list();
    		if (results != null && !results.isEmpty()) {
    			log(ERROR,
    					"Email id already in use.Please use different id or login using the same");
    			throw new Exception(
    					"Email id already in use.Please use different id or login using the same");
    		}*/

    		
    		account.setEmail(account.getEmail().toLowerCase());
    		account.setAccountId(account.getAccountId());
    		account.setUpdatedBy("SYS");
    		Calendar startingCalendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
    		account.setUpdatedTs(startingCalendar.getTime());
    		account.setActive(true);
    		account.setAccountRole("CUSTOMER");
    		session.update(account);

    	
    		System.out.println("customer::" + account.getFirstName());

    		log(INFO, "Returning *********************" + result);

    		db.commit();
    		result = "User data updated successfully";
    	} catch (Exception e) {
    		db.rollback();
    		log(ERROR, "Error during user data update", e);
    		throw e;
    	}
    	return account;


     }

	public class UserDetails {

	private boolean isAuthenticated;
	//private Account account=new Account();
	private String message;
	
	private String firstName;
	
	private String accountRole;
	
	private String email;
	
	private Integer accountId;
	
	private String lastName;
	
	private String cellPhone;
	
	private String password;
	
	private String address;
	

		
	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getCellPhone() {
		return cellPhone;
	}

	public void setCellPhone(String cellPhone) {
		this.cellPhone = cellPhone;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Integer getAccountId() {
		return accountId;
	}

	public void setAccountId(Integer accountId) {
		this.accountId = accountId;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getAccountRole() {
		return accountRole;
	}

	public void setAccountRole(String accountRole) {
		this.accountRole = accountRole;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public boolean isAuthenticated() {
		return isAuthenticated;
	}

	public void setAuthenticated(boolean isAuthenticated) {
		this.isAuthenticated = isAuthenticated;
	}

	
	

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	}	
}
